/*
 * tcpClient.java
 *
 * Created on March 26, 2006, 7:28 PM
 *
 * To change this template, choose Tools | Options and locate the template under
 * the Source Creation and Management node. Right-click the template and choose
 * Open. You can then make changes to the template in the Source Editor.
 */

/**
 *
 * @author Sujal Bista
 */

import java.net.*;
import java.io.*;

public class tcpClient extends Thread 
{
    
    //teh judge class
    private judge jud;
    
    private Socket socket = null;
        
    private String lineRead,inSocket,outSocket;

    //keyboard input
    private BufferedReader keyInput;

    //socket input output
    private BufferedReader socketInput;
    private PrintWriter socketOutput;

    //to record time stamp
    private java.sql.Timestamp time;

    //type of judge
    //private judge.judgeType jType;

    //Signature of judge
    private String jSign;
    
    /** Creates a new instance of tcpClient */
    public tcpClient() {
        
        //read setup file
        readSetupFile setup=new readSetupFile();
             
	socket = null;
        
        keyInput = new BufferedReader(new InputStreamReader(System.in)); 
        
        jSign="Auth Key";

        jud=new judge(judge.judgeType.judgeA,jSign);

        System.out.println("Server Address : " +  setup.getServerName().toString());
        System.out.println("Port no : " +  setup.getPortNum());

        try 
        {
            // connect to server
            socket = new Socket(setup.getServerName(),setup.getPortNum());
            System.out.println("Connected with server :" + socket.getInetAddress() + ":" + socket.getPort());

            socketInput = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
            socketOutput = new PrintWriter(socket.getOutputStream(),true);
        }
	catch (IOException e) 
        {
	    System.out.println(e);
	    System.exit(1);
	}

        time= new java.sql.Timestamp(System.currentTimeMillis());

        //init packet
        switch(globalData.judgeType)
        {
            case 1: //judge A   
            {
                socketOutput.println("INIT judgeA "+jSign);
                break;
            }
            case 2: //judge B
            {
                socketOutput.println("INIT judgeB "+jSign);
                break;
            }
            case 3: //judge C
            {
                socketOutput.println("INIT judgeC "+jSign);            
                break;
            }
        }
    }
    
    public synchronized void sendJudgeType()
    {
        switch(globalData.judgeType)
        {
            case 1: //judge A   
            {
                socketOutput.println("JTYPE judgeA");
                break;
            }
            case 2: //judge B
            {
                socketOutput.println("JTYPE judgeB");
                break;
            }
            case 3: //judge C
            {
                socketOutput.println("JTYPE judgeC");            
                break;
            }
        }
    }
    
    public synchronized void sendMessage(String message) 
    {
        time.setTime(System.currentTimeMillis());
        jud.updateAthelete(message);
        message="DATA "+message;
        System.err.println("Sending message: " + message);
        socketOutput.println(message);        
    }
    
    public void run()
    {
        try 
        {
	    // get user input and transmit it to server
	    while(true) 
            {
                if(socketInput.ready())
                {
                    inSocket=socketInput.readLine();
                    processPacket(inSocket);
                    System.out.println(inSocket);
                }

                if(keyInput.ready())
                {
                    lineRead = keyInput.readLine();
                    //time.setTime(System.currentTimeMillis());
                                     
                    // stop if input line is "."
                    if(lineRead.equals("."))
                        break;
                }
                try {
                    sleep(10);
                } catch (java.lang.InterruptedException e) {}
	    }
                        
            socket.close();
	}
	catch (IOException e) 
        {
	    System.out.println(e);
	    System.exit(1);
	}
    }
    
    private void processPacket(String packet)
    {
        //new athlete initiated
        if(packet.startsWith("ATHL"))
        {
            //removes the commmand
            packet=packet.substring(5);
           
            //check the judging type
            if(packet.substring(0, packet.indexOf(" ")).equals("0"))
            {
                //if(globalData.scoringSystem!=0)
                {
                    globalData.scoringSystem=0;
                    globalData.judgeType=globalData.judgeNumberToJudgeType(globalData.defaultJudgeType);
                    sendJudgeType();
                }
            }
            else  if(packet.substring(0, packet.indexOf(" ")).equals("1"))
            {
                //if(globalData.scoringSystem!=1)
                {
                    globalData.scoringSystem=1;
                    globalData.judgeType=globalData.judgeNumberToJudgeType(globalData.defaultJudgeType);
                    sendJudgeType();
                }
            
            }else
            {
               // if(globalData.scoringSystem!=2)
                {
                    globalData.scoringSystem=2;
                    globalData.judgeType=globalData.judgeNumberToJudgeType(globalData.defaultJudgeType);
                    sendJudgeType();
                }
            }
            globalData.setScreen();
            packet=packet.substring(packet.indexOf(" ")+1);
            
            //later on need to decypther the packet
            globalData.currentAthlete.fromString(packet);
            
            jud.beginAthlete(globalData.currentAthlete.getName());
            System.out.println(globalData.currentAthlete.getName());
            
            globalData.ButtonInput1.setEnabled(true);
            globalData.BoxInput.setEnabled(true);
            globalData.BoxInput.setText("");
            
            globalData.TextArea.setEnabled(true);

            //setup the front screen
            globalData.TextArea.setText(globalData.currentAthlete.getEvent()+"\n");
            globalData.TextArea.append(globalData.currentAthlete.getGroup()+"\n");
            globalData.TextArea.append(globalData.currentAthlete.getName()+"\n");
            for(int i=0;i<globalData.currentAthlete.getNanduCount();i++)
            {
                String nanduCode=globalData.currentAthlete.getNandu(i);
                nanduData.nandu nanduDesc=globalData.nanduList.find(nanduCode);
                if(nanduDesc!=null)
                {
                    globalData.TextArea.append(Integer.toString(i+1)+" : "+nanduDesc.description);
                    globalData.TextArea.append("\n");
                    for(int j=0;j<nanduDesc.getTotalMovements();j++)
                    {                    
                        globalData.TextArea.append(nanduDesc.getCode(j)+"\t");
                    }
                    globalData.TextArea.append("\n\n");
                }
            }
            globalData.TextArea.append("\n");
            
            globalData.numButtonPressed=0;
            globalData.BoxInput.grabFocus();
            //globalData.Caption2.setText(globalData.currentAthlete./);
            globalData.nanduResults.clear();            
            
        }
        else if (packet.startsWith("SCOR"))
        {
            //removes the commmand
            packet=packet.substring(5);
            //check the judging type
            if(packet.equals("0"))
            {
                globalData.scoringSystem=0;
                globalData.judgeType=globalData.judgeNumberToJudgeType(globalData.defaultJudgeType);
                sendJudgeType();
            }
            else  if(packet.equals("1"))
            {
                globalData.scoringSystem=1;
                globalData.judgeType=globalData.judgeNumberToJudgeType(globalData.defaultJudgeType);
                sendJudgeType();
            }else
            {
                globalData.scoringSystem=2;
                globalData.judgeType=globalData.judgeNumberToJudgeType(globalData.defaultJudgeType);
                sendJudgeType();
            }
            globalData.setScreen();
            //disable them
            globalData.CaptionInput.setEnabled(false);
            globalData.BoxInput.setEnabled(false);
            globalData.ButtonInput1.setEnabled(false);
            globalData.ButtonInput2.setEnabled(false);
            globalData.ButtonInput4.setEnabled(false);
            globalData.ButtonInput3.setEnabled(false);
            
        }
        else if (packet.startsWith("EVNT"))
        {
            packet = packet.substring(5);
            globalData.currentAthlete.UnmarshalGroupGenderEvent(packet);
            //setup the front screen
            globalData.TextArea.setText(globalData.currentAthlete.getEvent()+"\n");
            globalData.TextArea.append(globalData.currentAthlete.getGroup()+"\n");
            globalData.TextArea.append(globalData.currentAthlete.getName()+"\n");
            for(int i=0;i<globalData.currentAthlete.getNanduCount();i++)
            {
                String nanduCode=globalData.currentAthlete.getNandu(i);
                nanduData.nandu nanduDesc=globalData.nanduList.find(nanduCode);
                if(nanduDesc!=null)
                {
                    globalData.TextArea.append(Integer.toString(i+1)+" : "+nanduDesc.description);
                    globalData.TextArea.append("\n");
                    for(int j=0;j<nanduDesc.getTotalMovements();j++)
                    {                    
                        globalData.TextArea.append(nanduDesc.getCode(j)+"\t");
                    }
                    globalData.TextArea.append("\n\n");
                }
            }
            globalData.TextArea.append("\n");
        }
        else if(packet.startsWith("ATFN"))  //data regarding athlete is closed
        {
            //removes the commmand
           // packet=packet.substring(5);
            
            //close the athlete
            jud.endAthlete();
            
            globalData.CaptionInput.setEnabled(false);
            globalData.BoxInput.setEnabled(false);
            globalData.ButtonInput1.setEnabled(false);
            globalData.ButtonInput2.setEnabled(false);
            globalData.ButtonInput4.setEnabled(false);
            globalData.ButtonInput3.setEnabled(false);
            
            System.out.println(packet);
        }
    }
    
}
